<?php
namespace yan\googlesitemapgenerator\controllers;
use Yii;
use common\models\dao\Module;
use common\models\dao\ModuleConfig;

use yii\web\NotFoundHttpException;

class DefaultController extends \backend\components\controllers\CController{
	public function actionIndex($id){
		
		$model = $this->findModel($id);
		$formModels = ModuleConfig::find()->where(['key'=>'content', 'code'=>$model->code])->one();
        $formModels = empty($formModels) ? new ModuleConfig(['key'=>'content', 'code'=>$model->code]) : $formModels;
		$list['urlReferrer'] = \Yii::$app->request->referrer;

		if(Yii::$app->request->isPost ){
            $list['urlReferrer'] = Yii::$app->request->post('urlReferrer');

            $flag = $this->doSave($model, $formModels,Yii::$app->request->post() );
            
            if( $flag ){
                Yii::$app->getSession()->setFlash('success', Yii::t('extensions','Successful'));
                
                return strpos($list['urlReferrer'], Yii::$app->controller->action->id)==0 ? $this->redirect($list['urlReferrer']) : $this->redirect(['/frontendmodule/default', 'type' => $model->type]);
            }
        }

        return $this->render('index', [
            'list'=>$list, 
            'model'=>$model, 
            'formModels'=> Yii::$app->request->isPost ? Yii::$app->request->post() : (empty($formModels->value) ? [] : json_decode($formModels->value, true)),
        ]);
    }

	// 保存操作
    protected function doSave($model, &$formModels, $input=null){
        $transaction = Yii::$app->db->beginTransaction();

        if(!empty($input)){
            try {
                $i = 0;
                $ids = [];
                
                $formModels->value = json_encode(Yii::$app->request->post());
                $formModels->save();
                
                $transaction->commit();
                return true;
                

            } catch (\Exception $e) {
                $transaction->rollback();
                Yii::$app->getSession()->setFlash('error', $e->getMessage());
            }
            
        }else{
        	Yii::$app->getSession()->setFlash('error', Yii::t('extensions', 'Content cannot be blank.'));
        }
        return false;
    }

    protected function findModel($id)
    {
        if (($model = Module::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}